class Dictionary < ActiveRecord::Base
  validates_presence_of :word
  validates_uniqueness_of :word, :scope => :flag
  validates_numericality_of :rank
  
  attr_accessor :import_file
  
  FLAGS = { 0 => '分词词库', 1 => '垃圾词库' }
  
  named_scope :valid, :conditions => ['status >= ?', 0]
  
  named_scope :filter, lambda { |params|
    c, h = [], {}
    
    unless params[:id].blank?
      c << "id LIKE :id"
      h[:id] = "%#{params[:id]}%"
    end
    unless params[:word].blank?
      c << "word LIKE :word"
      h[:word] = "%#{params[:word]}%"
    end
    unless params[:flag].blank?
      c << "flag = :flag"
      h[:flag] = params[:flag]
    end
    
    { :conditions => [c.join(' AND '), h] }
  }
  
  class << self
  
    def flag_options
      FLAGS.inject([]){ |arr, obj| arr << obj.reverse }
    end
    
    # import file encode must be utf8
    def import(file, flag = 0)
      return false if file.blank? or File.extname(file.original_filename) != ".txt"
      
      require 'iconv'
      file.readlines.each do |line|
        #word = Iconv.conv("utf8//IGNORE","GBK//IGNORE", line.strip)
        word = line.strip
        next if word =~ /^#/

        puts "Word: #{word}"
        find_or_create_by_word_and_flag(word, flag.to_i)
      end
      true
    end
  end
  
  def to_s
    word
  end
  
  def display_flag
    FLAGS[flag]
  end
  
  def del
    update_attributes!(:status => -1)
  end
end
